package com.vip.jwt.controller;


import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.vip.jwt.aop.SysLog;
import com.vip.jwt.common.entity.R;
import com.vip.jwt.entity.Role;
import com.vip.jwt.entity.User;
import com.vip.jwt.service.RoleService;
import com.vip.jwt.service.UserRoleService;
import com.vip.jwt.service.UserService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.List;

/**
 * <p>
 * 用户表 前端控制器
 * </p>
 *
 * @author vip
 * @since 2021-05-04
 */
@RestController
@RequestMapping("/api/user")
public class UserController {

    @Resource
    private UserService userService;

    @Resource
    private UserRoleService userRoleService;

    @SysLog(desc = "添加用户")
    @PostMapping
    public Object addUser(@RequestBody @Valid User user){
        userService.saveUser(user);
        return R.ok();
    }

    @SysLog(desc = "删除用户")
    @DeleteMapping("/{id}")
    public Object deleteById(@PathVariable String id){
        userService.deleteById(id);
        return R.ok();
    }

    @SysLog(desc = "更新用户")
    @PutMapping
    public Object updateUser(@RequestBody User user){
        userService.updateUser(user);
        return R.ok();
    }

    @GetMapping("/{page}/{limit}")
    public Object page(@PathVariable Long page,@PathVariable Long limit){
        Page<User> userPage = new Page<>(page,limit);
        userPage = userService.page(userPage);
        List<User> users = userPage.getRecords();
        for(int i=0;i<users.size();i++){
            User user = users.get(i);
            String userId = user.getId();
            List<Role> roles = userRoleService.findByUserId(userId);
            user.setRoles(roles);
        }
        return R.ok().data("data",userPage);
    }

}

